<?php
namespace app\common\model;

class KpiRecord extends Base
{
    /**
     * 更新KPI数据
     */
    public static function setKpiData($date = '2022-4')
    {
        if(empty($date)) $date = date('Y-m');
        /** 需要更新数据的员工 */
        $kpiList = KpiRecord::whereMonth('data_time', $date)->field('id, user_id, rule_kpi_id, total_target, total, daily')->select();

        foreach($kpiList as $info){
            /** 总业绩 */
            $total = Job::setAchie($info['user_id'], $date);

            /** 业绩分数 */
            $frac = round($total / $info['total_target'] * 70);

            $dataInfo = [
                'id'         => $info['id'],
                'total'      => $total,
                'radio'      => $info['total_target'] * 0.3 < $total ? RuleKpi::getVal(['id' => $info['rule_kpi_id']], 'radio') : 0,
                'total_frac' => $frac,
                'score'      => $frac + $info['daily'],
                'grade'      => OkrRecord::getGrade($frac + $info['daily']),
            ];

            $data[] = $dataInfo;
        }

        /** 更新KPI数据 */
        (new KpiRecord())->saveAll($data);
    }
}